<?php

/**
 * This is the model class for table "{{user}}".
 *
 * The followings are the available columns in table '{{user}}':
 * @property integer $ID
 * @property string $username
 * @property string $password
 * @property integer $active
 * @property integer $reset
 * @property integer $createddate
 * @property integer $modifieddate
 * @property integer $deleted
 * @property integer $status
 */
class User extends CActiveRecord
{
	public $repass;
	public $oldpass;
	public $captcha;
	public $fullname;
	public $userstatus;
	public $roleID;
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return User the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{user}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('username', 'required','on'=>'register,create'),
			array('username','validateUsername','on'=>'register,create'),
			array('oldpass','validateOldpass','on'=>'update_profile,update'),
			array('password','validatePassword','on'=>'update_profile,update'),
			array('password, repass', 'required','on'=>'register,create'),
			array('password', 'length', 'min'=>5),
			array('repass','compare','compareAttribute'=>'password'),
			array('roleID','required','on'=>'create,update'),
			
			array('active, reset, createddate, modifieddate, deleted, status', 'numerical', 'integerOnly'=>true),
			array('username, password', 'length', 'max'=>255),
			
			array('captcha','required','on'=>'reset'),
		  array('captcha','captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(),'on'=>'reset'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('ID, username, password, active, reset, createddate, modifieddate, deleted, status', 'safe', 'on'=>'search'),
		);
	}
  /**
   * Check username if duplicate
   */
	public function validateUsername($att, $param) {
	  $this->username = strtolower(trim($this->username));
	  $user = User::model()->find(array('condition'=>'LCASE(`username`)=:username','params'=>array(':username'=>$this->username)));
	  if(!empty($user)) {
	    $this->addError('username', 'Tên đăng nhập này đã tồn tại');
	    return false;
	  }
	  return true;
	}
	/**
	 * User update profile, if change password, check oldpass
	 */
	public function validateOldpass($att, $param) {
	  $oldpass = $this->oldpass;
	  $password = User::model()->findByPk($this->ID);
	  if($this->password!="" && $oldpass=="") {
	    $this->addError('oldpass', 'Mật khẩu cũ không thể trống');
	    return false;
	  }
	  if($oldpass!="" && $oldpass!=$password->password && !empty($password)) {
	    $this->addError('oldpass', 'Mật khẩu cũ không chính xác');
	    return false;
	  }
	  return true;
	}
	/**
	 * User update profile, if change password, input new password
	 */
	public function validatePassword($att, $param) {
	  if($this->oldpass!="" && $this->password=="") {
	    $this->addError('password', 'Mật khẩu mới không thể trống');
	    return false;
	  }
	  return true;
	}
	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
	  $password = "Mật khẩu";
	  $repass = "Xác nhận mật khẩu";
	  if($this->getScenario()=="update") {
	    $password = "Mật khẩu mới";
	    $repass = "Xác nhận mật khẩu mới";
	  }
		return array(
			'ID' => 'ID',
			'username' => 'Tên đăng nhập',
		  'oldpass'=>'Mật khẩu cũ',
			'password' => $password,
		  'repass'=> $repass,
			'active' => 'Kích hoạt',
			'reset' => 'Reset',
			'createddate' => 'Ngày tạo',
			'modifieddate' => 'Ngày cập nhật',
			'deleted' => 'Deleted',
			'status' => 'Trạng thái',
			'fullname'=>'Họ tên',
			'captcha'=> 'Mã xác nhận',
		  'roleID'=>'Quyền',
		);
	}
	
	protected function beforeSave() {
		if($this->isNewRecord) {
			$this->createddate = time();
		}
			$this->modifieddate = time();
		return parent::beforeSave();
	}
	
	public function getYesNo($type) {
		$string = "";
		if($type==1) {
			$string = "Có";
		} else {
			$string = "Không";
		}
		return $string;
	}
	
  public function getUserStatus($userID) {
		$string = "";
		
	  //$userstatus = UserStatus::model()->findByAttributes(array('userID'=>$userID));	
		$userstatus = Yii::app()->db->createCommand()
		            ->select('stt.status')
		            ->from('tbl_user_status ut')
		            ->join('tbl_status stt', 'stt.statusID=ut.statusID')
		            ->where('ut.userID='.$userID)
		            ->queryRow();
	  
		if(!empty($userstatus)) {
		  $string = $userstatus['status'];
		}
		return $string;
	}
	
	public function getUserName($userID) {
		$username = "";
		$user = Yii::app()->db->createCommand()
		            ->select('u.username')
		            ->from('tbl_user u')
		            ->where('u.ID='.$userID)
		            ->queryRow();
	  
		if(!empty($user)) {
		  $username = $user['username'];
		}
		return $username;
	}
	
  public function getFullname($userID) {
    $string = "";
    $userprofile = UserProfile::model()->findByAttributes(array('userID'=>$userID));
    if(!empty($userprofile))
    {
      $string = $userprofile->fullname;
    }
    else {
      $string = $userID; 
    }
    return $string;
  }
  
  /**
   * get all roles in tbl_role
   * @author K.D
   */
  public function getAllRole() {
    $array = array();
    $all_roles = Role::model()->findAllByAttributes(array('enabled'=>1),array('order'=>'role'));
    if(!empty($all_roles)) {
      foreach ($all_roles as $role) {
        $array[$role->ID] = $role->role." <a class='tip icon-question-sign' rel='tooltip' title='$role->description'></a>";
      }
    }
    return $array;
  }
  
  /**
   * get role of user
   * @author K.D
   */
  public function getRole() {
    $string = "";
    $userrole = Yii::app()->db->createCommand()
              ->select('r.role')
              ->from('tbl_user t')
              ->join('tbl_user_role ur','t.ID=ur.userID')
              ->join('tbl_role r','r.ID=ur.roleID')
              ->where('t.ID='.$this->ID)
              ->queryAll();
    if(!empty($userrole)) {   
      $string .= "<ul>"; 
      foreach ($userrole as $ur) {
        $string .= "<li>".$ur['role']."</li>";
      }
      $string .= "</ul>";
    }
    return $string;
  }
  
	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;
		$criteria->together = true;
		$criteria->select = 't.*,up.fullname as fullname,stt.status as userstatus';
		$criteria->join = 'JOIN tbl_user_profile as up ON t.ID=up.userID 
							JOIN tbl_user_status as ut ON t.ID=ut.userID JOIN tbl_status as stt ON stt.statusID=ut.statusID';
		$criteria->condition = 't.deleted=0';
		$criteria->compare('username',trim($this->username),true);
		if(isset($_GET['User']['fullname']) && !empty($_GET['User']['fullname'])) {
  		$criteria->compare('fullname',trim($_GET['User']['fullname']),true);
		}
		$criteria->compare('active',$this->active);
		$criteria->compare('reset',$this->reset);
		$criteria->compare('stt.status',$this->status,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'sort'=>array(
        'attributes'=>array(
            'fullname'=>array(
                'asc'=>'fullname',
                'desc'=>'fullname DESC',
            ),
            '*',
        ),
   		),
		));
	}
}